package com.mlamp.低复杂度操作;

import com.mlamp.排序算法.基础排序;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Vector;

public class O1操作复杂度 {

    private static Vector<Integer> vector = new Vector<>();
    private static Map<Integer, Integer> val2Index = new HashMap<>();

    public static void main(String[] args) {
        int[] ints = 基础排序.generateArray(30);
        for (int i = 0; i < ints.length; i++) {
            insert(ints[i]);
        }
    }

    /**
     * 返回插入的位置
     *
     * @param value
     * @return
     */
    public static int insertA(int value) {
        //如果存在，直接返回元素的位置
        if (val2Index.containsKey(value)) return val2Index.get(value);
        //否则，返回vector的最新长度
        int size = vector.size();
        vector.add(value);
        val2Index.put(value, size);
        return size;
    }

    public static void insert(int value) {
        if (val2Index.containsKey(value)) return;
        vector.add(value);
        val2Index.put(value, vector.size());
    }

    public static void remove1(int value) {
        Integer location = val2Index.get(value);
        int end = vector.get(vector.size() - 1);
        vector.set(location, end);
        val2Index.put(end, location);
        vector.remove(vector.size() - 1);
        val2Index.remove(value);
    }

    public static int random1() {
        int size = vector.size();
        return vector.get((int) (Math.random() * size));
    }


    public static void removeA(int value) {
        if (!val2Index.containsKey(value)) throw new IllegalStateException(String.format("value=%d not exists", value));
        Integer location = val2Index.get(value);
        Integer integer1 = vector.get(vector.size() - 1);
        val2Index.put(integer1, location);
        vector.set(location, integer1);
        vector.set(vector.size() - 1, value);
        vector.remove(vector.size() - 1);
        val2Index.remove(value);
    }


    public static void remove(int value) {
        Integer loc = val2Index.get(value);
        int end = vector.get(vector.size() - 1);
        vector.add(loc, end);
        val2Index.put(end, loc);
        vector.remove(vector.size() - 1);
        val2Index.remove(value);
    }

    public static int randomA() {
        return vector.get((int) (Math.random() * vector.size()));
    }

    public static int random() {
        int size = vector.size();
        return vector.get((int) (Math.random() * size));
    }


}
